package top.houry.im.client.event;

import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.houry.im.client.controller.ImClientMainUiController;
import top.houry.im.client.listener.ImClientNettyProcessorListener;
import top.houry.im.client.proto.ImMessage;
import top.houry.im.client.utils.ImClientChannelUtils;
import top.houry.im.ui.interfaces.ImUiLoginEvent;

public class ImClientUiLoginEvent implements ImUiLoginEvent {
    private static final Logger log = LoggerFactory.getLogger(ImClientUiLoginEvent.class);

    @Override
    public void login(String userId, String password) {
        log.info("[Req]-[ImClientUiLoginEvent]-[login]-[userId:{}]-[password:{}]", userId, password);
        ChannelHandlerContext ctx = ImClientChannelUtils.getChannelHandlerContext();
        if (!ImClientChannelUtils.checkIsAvailable(ctx)) {
            log.info("[ImClientUiLoginEvent]-[login]-[根据userId:{}]-[获取的通道为空]", userId);
            return;
        }

        ImMessage.LoginReqMessage.Builder loginReq = ImMessage.LoginReqMessage.newBuilder();
        loginReq.setUserId(userId);
        loginReq.setPassword(password);

        ImMessage.Client.Builder client = ImMessage.Client.newBuilder();
        client.setMsgType("client.login.req");
        client.setBytesData(loginReq.build().toByteString());

        ctx.writeAndFlush(client).addListener(new ImClientNettyProcessorListener("客户端登录请求"));

        ImClientMainUiController.getInstance().setUserInfo(userId, "houry");

    }
}
